<template>
  <!--  show-heade 是否显示表头-->
  <div>
    <div class="checkAll">
      <span>全选</span>
      <input type="checkbox" v-model="isCheckAll" @change="checkAll(tableData)" />
    </div>
<!--    结算按钮-->
    <div class="account">
      <el-button @click="buy()">
        结算
      </el-button>
    </div>
  <el-table
    :show-header="showHeader"
    :data="tableData"
    stripe
  >
    <!--    在el-table-column中用prop属性来对应对象中的键名即可填入数据，-->
    <!--    用label属性来定义表格的列名。-->
    <!--    可以使用width属性来定义列宽。-->
    <!-- 勾选框列   -->
    <el-table-column>
      <template slot-scope="scope" >
        <input type="checkbox" v-model="scope.row.check" @change="check(scope.$index,tableData)" />
      </template>
    </el-table-column>
    <!-- 产品数据   -->
    <el-table-column
      v-for="col in columnHeaders" :key="col.prop" :prop="col.prop" :label="col.label"
    >
    </el-table-column>
    <!-- 产品数量   -->
    <el-table-column :label="numLabel">
      <template slot-scope="scope">
        <el-input-number class="number" size="mini" :min="1" placeholder="1" v-model="scope.row.number" @change="numChange"></el-input-number>
      </template>
    </el-table-column>
    <!--  删除按钮  -->
    <el-table-column>
      <template slot-scope="scope">
        <el-button @click.native.prevent="deleteRow(scope.$index, tableData)">
          删除此项
        </el-button>
      </template>
    </el-table-column>
  </el-table>
    <div>
      <span>总计:{{sum}}</span>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ShoppingCartTable',
  watch: {

  },
  methods: {
    deleteRow (index) {
      this.tableData.splice(index, 1)
      this.account(this.tableData)
      this.save()
      location.reload()
    },
    save () {
      let xmlhttp = new XMLHttpRequest()
      xmlhttp.open('POST', 'http://127.0.0.1:3100/users/refreshShoppingCart')
      xmlhttp.setRequestHeader('content-type', 'application/json')
      let data = {id: this.ID, cartBooks: this.saveItems()}
      xmlhttp.onreadystatechange = function (res) {
        if (xmlhttp.readyState === 4) {
          if (xmlhttp.status === 200) {
            console.log('购物车已保存')
          }
        }
      }
      xmlhttp.send(JSON.stringify(data))
    },
    saveItems () {
      let items = []
      console.log(this.tableData.length)
      for (var i = 0; i < this.tableData.length; i++) {
        let tem = {bookName: this.tableData[i].name, price: this.tableData[i].price, buyNum: this.tableData[i].number}
        items.push(tem)
      }
      return items
    },
    // 购买按钮函数
    buy () {
      for (var i = 0; i < this.tableData.length; i++) {
        if (this.tableData[i].check === true) {
          this.tableData.splice(i, 1)
          i--
        }
      }
      this.addToHistory()
      this.refreshScore()
      this.save()
      location.reload()
    },
    addToHistory () {
      let that = this
      let xmlhttp = new XMLHttpRequest()
      xmlhttp.open('POST', 'http://127.0.0.1:3100/users/addToHistory')
      xmlhttp.setRequestHeader('content-type', 'application/json')
      let data = {id: this.ID, book: this.buyItems}
      console.log('buyItems', this.buyItems)
      xmlhttp.onreadystatechange = function (res) {
        if (xmlhttp.readyState === 4) {
          if (xmlhttp.status === 200) {
            console.log('tem', that.buyItems)
            console.log('已提交')
          }
        }
      }
      xmlhttp.send(JSON.stringify(data))
    },
    refreshScore () {
      let that = this
      let xmlhttp = new XMLHttpRequest()
      xmlhttp.open('POST', 'http://127.0.0.1:3100/users/updatePoints')
      xmlhttp.setRequestHeader('content-type', 'application/json')
      let score = this.score_existing - this.sum
      let data = {id: this.ID, points: score}

      xmlhttp.onreadystatechange = function (res) {
        if (xmlhttp.readyState === 4) {
          if (xmlhttp.status === 200) {
            that.score_existing = that.score_existing - that.sum
            console.log(that.score_existing)
            alert('已购买')
          }
        }
      }
      xmlhttp.send(JSON.stringify(data))
    },
    account () {
      this.sum = 0
      this.buyItems = []
      for (var i = 0; i < this.tableData.length; i++) {
        if (this.tableData[i].check === true) {
          this.sum += this.tableData[i].price * this.tableData[i].number
          let item = {bookName: this.tableData[i].name, price: this.tableData[i].price, buyNum: this.tableData[i].number, dealStatus: '已购买'}
          this.buyItems.push(item)
        }
      }
      console.log('abcd', this.buyItems)
    },
    checkAll (tableData) {
      if (this.isCheckAll === true) {
        for (var i = 0; i < tableData.length; i++) {
          console.log(tableData[i])
          console.log(tableData[i].check)
          tableData[i].check = true
        }
      } else {
        for (var j = 0; j < tableData.length; j++) {
          console.log(tableData[j])
          console.log(tableData[j].check)
          tableData[j].check = false
        }
      }
      this.account(tableData)
    },
    check (index, tableData) {
      console.log(tableData[index].check)
      this.account(tableData)
    },
    numChange () {
      this.account(this.tableData)
    }
  },
  data () {
    return {
      ID: localStorage.getItem('userID'),
      isCheckAll: false,
      sum: 0,
      numLabel: '数量',
      buyItems: []
    }
  },
  props: {
    tableData: {
      required: true
    },
    columnHeaders: {
      required: true
    },
    showHeader: {
      required: false,
      type: Boolean,
      default: true
    },
    score_existing: {
      required: true
    }
  }
}
</script>

<style scoped>
  .checkAll{
    float: left;
  }
  .account{
    float: right;
    margin-right: 12%;
  }

</style>
